package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.DishMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkSpaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkSpaceService workSpaceService;

    /**
     * 统计指定时间区间内的营业额数据
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        //统计begin到end之间的日期
        List<LocalDate> dateList = new ArrayList<>();
        while (!begin.equals(end)) {
            //日期计算
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
        dateList.add(end);

        //存放每天的营业额
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            //每天的起始时间：00：00：00
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            //每天的结束时间：23：59：59.9999999
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            //select sum(amount) from orders where status = 5 and order_time between beginTime and endTime
            Map<String, Object> map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.getSumByMap(map);
            //判断当天营业额是否为null，如果为null则转换为0.0
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }

        //封装结果数据
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    /**
     * 统计指定时间区间内的用户数据
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        //统计begin到end之间的日期
        List<LocalDate> dateList = new ArrayList<>();
        while (!begin.equals(end)) {
            //日期计算
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
        dateList.add(end);

        //存放每天新增的用户量
        List<Integer> newUserList = new ArrayList<>();
        //存放每天总的用户量
        List<Integer> totalUserList = new ArrayList<>();

        for (LocalDate date : dateList) {
            //每天的起始时间：00：00：00
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            //每天的结束时间：23：59：59.9999999
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Map<String, Object> map = new HashMap<>();
            map.put("end", endTime);
            //总用户量
            Integer totalUser = userMapper.getByMap(map);
            //判断当天总用户量是否为null，如果为null则转换为0
            totalUser = totalUser == null ? 0 : totalUser;
            totalUserList.add(totalUser);

            map.put("begin", beginTime);
            //新增用户量
            Integer newUser = userMapper.getByMap(map);
            //判断当天新增用户量是否为null，如果为null则转换为0
            newUser = newUser == null ? 0 : newUser;
            newUserList.add(newUser);
        }

        //封装结果数据
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .build();
    }

    /**
     * 统计指定时间区间内的订单数据
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        //统计begin到end之间的日期
        List<LocalDate> dateList = new ArrayList<>();
        while (!begin.equals(end)) {
            //日期计算
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
        dateList.add(end);

        //存放每日订单数
        List<Integer> orderCountList = new ArrayList<>();
        //存放每日有效订单数
        List<Integer> validOrderCountList = new ArrayList<>();
        //记录订单总数
        Integer totalOrderCount = 0;
        //记录有效订单总数
        Integer validOrderCount = 0;

        for (LocalDate date : dateList) {
            //每天的起始时间：00：00：00
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            //每天的结束时间：23：59：59.9999999
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            //计算每天订单数
            Map<String, Object> map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);
            Integer totalCount = orderMapper.getCountByMap(map);
            orderCountList.add(totalCount);

            //总订单数加上每天订单数
            totalOrderCount += totalCount;

            //计算每天有效订单数
            map.put("status", Orders.COMPLETED);
            Integer validCount = orderMapper.getCountByMap(map);
            validOrderCountList.add(validCount);

            //总有效订单数加上每天有效订单数
            validOrderCount += validCount;
        }

        //订单完成率
        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0) {
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }

        //封装结果对象
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 统计指定时间区间内的销量排名tap10
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getSalesTap10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(beginTime, endTime);

        StringBuilder nameList = new StringBuilder();
        StringBuilder numberList = new StringBuilder();

        if (salesTop10 != null && salesTop10.size() > 0) {
            for (int i = 0; i < salesTop10.size(); i++) {
                GoodsSalesDTO goodsSalesDTO = salesTop10.get(i);
                if (i < salesTop10.size() - 1) {
                    nameList.append(goodsSalesDTO.getName()).append(",");
                    numberList.append(goodsSalesDTO.getNumber()).append(",");
                } else {
                    nameList.append(goodsSalesDTO.getName());
                    numberList.append(goodsSalesDTO.getNumber());
                }
            }
        }

        return new SalesTop10ReportVO(nameList.toString(), numberList.toString());
    }

    /**
     * 导出Excel报表接口
     * @param response
     */
    @Override
    public void exportBusinseeDate(HttpServletResponse response) {
        //获取数据---获取最近30天的数据
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);

        BusinessDataVO businessDataVO = workSpaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));
        //通过POI将数据写Excel报表
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            //基于模板文件创建一个新的Excel文件
            XSSFWorkbook excel = new XSSFWorkbook(in);

            //获取表格的Sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");

            //填充数据---时间
            sheet.getRow(1).getCell(1).setCellValue("时间：" + begin + "至" + end);

            //填充概览数据
            //获得第4行
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());

            //获得第5行
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());

            //填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);
                //查询某一天的营业数据
                BusinessDataVO everydayData = workSpaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                row = sheet.getRow(i + 7);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(everydayData.getTurnover());
                row.getCell(3).setCellValue(everydayData.getValidOrderCount());
                row.getCell(4).setCellValue(everydayData.getOrderCompletionRate());
                row.getCell(5).setCellValue(everydayData.getUnitPrice());
                row.getCell(6).setCellValue(everydayData.getNewUsers() );
            }

            //通过输出流将Excel报表下载到客户游览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            out.close();
            excel.close();
            in.close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
